package com.play2gether;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Raul on 23/05/14.
 */
public class Sincronizar{
    private String id_usuario;
    private DataBaseManager db;
    private Context context;

    public Sincronizar(String id, Context c){
        id_usuario = id;
        context = c;
        db = new DataBaseManager(context);
    }

    public boolean sincronizar(){

        try                 { new obtenerEnviosPendientes().execute();  }
        catch (Exception e) { e.printStackTrace();
            Log.e("ERROR", e.getMessage());
        }
        return true;
    }
    public class obtenerEnviosPendientes extends AsyncTask<Void, Void, JSONObject> {

        protected void onPreExecute() {
            Toast.makeText(context.getApplicationContext(),"Sincronizando con el servidor", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected JSONObject doInBackground(Void... JSONObject) { // Segunda función. Nos devuelve el parámetro que viene del post se modificará todo lo gráfico que se hace en primer plano.

            String url = "http://mediadomeprojects.com/arkdyanbyte/play2gether/public/pooling";

            HttpClient cliente = new DefaultHttpClient();
            HttpPost htppost = new HttpPost(url);
            //BufferedReader bfr;
            String text = "Error";
            String result = "";
            InputStream is = null;
            JSONObject json = null;

            //Añadir parametros
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id1", id_usuario));

            try {
                htppost.setEntity(new UrlEncodedFormEntity(params));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                HttpResponse respuesta = cliente.execute(htppost);
                HttpEntity entity = respuesta.getEntity();
                is = entity.getContent();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
            }

            try {
                json = new JSONObject(result);
            } catch (JSONException e) {
            }
            return json;
        }

        protected void onPostExecute(JSONObject json) {
            try {
                boolean borrar = false;
                if (json!=null) {
                    try {
                        JSONObject datosSug = (JSONObject) json.get("sugerencias");
                        db.LlenarBBDDconDatosSugerencias(datosSug, id_usuario);
                        borrar = true;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    try {
                        JSONObject datosFor = (JSONObject) json.get("formularios");
                        db.LlenarBBDDconDatosFormularios(datosFor, id_usuario);
                        borrar = true;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    if (borrar) {
                        new borrarEnviosPendientes().execute();
                    }
                        Intent intent = new Intent(context, principalActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                }
                else{
                    Intent intent = new Intent(context, principalActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
    public class borrarEnviosPendientes extends AsyncTask<Void, Void, Void> {
        protected void onPreExecute(){}

        @Override
        protected  Void doInBackground(Void... Void) {

            String url = "http://mediadomeprojects.com/arkdyanbyte/play2gether/public/eliminar_envios";

            HttpClient cliente = new DefaultHttpClient();
            HttpPost htppost = new HttpPost(url);
            //BufferedReader bfr;
            String text = "Error";
            String result="";
            InputStream is = null;
            JSONObject json = null;

            //Añadir parametros
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("tipo_envio","1"));
            params.add(new BasicNameValuePair("id_usuario",id_usuario));

            try {
                htppost.setEntity(new UrlEncodedFormEntity(params));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                HttpResponse respuesta = cliente.execute(htppost);
                HttpEntity entity = respuesta.getEntity();
                is = entity.getContent();
                //text = EntityUtils.toString(entity);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute() {}
    }


}
